<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<!-- <view class="nav-bar">
			<view class="back-icon" @tap="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<view class="title">齐套点数</view>
		</view>
 -->
		<!-- 表单区域 -->
		<view class="form-container">
			<!-- 齐套区域 -->
			<view class="form-item">
				<view class="label">齐套区域：</view>
				<view class="value-wrapper">
					<picker
						class="value"
						:range="options" 
					    :range-key="'label'" 
					    @change="handlePickerChange"
						style="width: 100%;"
					>
						<view class="picker-box">
							{{ selectedLabel || '请选择' }}
					    </view>
					</picker>
				</view>
			</view>

			<!-- 存放编号 -->
			<!-- <view class="form-item">
				<view class="label">存放编号：</view>
				<view class="value-wrapper">
					<view class="value">请选择</view>	
				</view>
			</view> -->
			
			<!-- 扫码查询区域 -->
			<view class="scan-query-row">
				<button class="scan-btn" @tap="startScan">扫码</button>
				<view class="scan-input">
					<input v-model="productCodeInput" placeholder="工序条码、车间生产任务单" />
				</view>
				<button class="query-btn" @tap="onQuery">查询</button>
			</view>

			<!-- 任务单详情 -->
			<view class="task-details">
				<view class="detail-item">车间生产任务单：
				<text v-if="productData">{{productData.productBillNo}}</text>
				</view>
				<view class="detail-item">制品名称：
				<text v-if="productData">{{productData.goodsName}}</text>
				</view>
				<view class="detail-item">图号-规格/版本：
				<text v-if="productData">{{productData.designNumberVerSpec}}</text>
				</view>
				<view class="detail-item">未点数量：						
					<text v-if="productData">{{unpointedCount}}</text>
				</view>

				<!-- 数量信息 -->
				<view class="quantity-info">
					<view class="quantity-row">
						<text style="margin-left: 20rpx;">超额：</text>
						<text class="over-limit">{{overLimit}}</text>
						<text style="margin-left: 100rpx;">点数数量：</text>
						<input type="number" class="quantity-input" v-model="pointedCount" />
						<button class="unit-button" @tap="onAllNumber">全部</button>
						
					</view>
				</view>
			</view>

			<!-- 内容区域 -->
			<!-- view class="content-area">preview-image</view> -->
			<view>
				<image
					v-if="imageUrl"
					:src="imageUrl"
					mode="aspectFill"
					lazy-load
					class="content-area"
					@error="handleImageError()"
				/>
			</view>
			
			<!-- 底部区域 -->
			<view class="footer">
			    <button class="footer-btn" @tap="goToDetail">齐套列表</button>
			    <button class="footer-btn pdfActive" @tap="handleDownloadPdf">PDF图纸</button>
			    <button class="footer-btn" @tap="handleSave">确认</button>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { LAN_URL, DOWNLOAD_BASE } from '@/pages/config/global';

const GET_PRODUCT_URL = '/kitting/getProduct'
const FILE_URL = '/kitting/getProductPDF'
const QUERY_WA_URL = '/kitting/queryWaCode'
const ADD_URL = '/kitting/addStorageArea'

const emits = defineEmits(['update']);

// 数据绑定
const userID = ref('');
const productCodeInput = ref<string>('');
const productData = ref<pd>(null);
const unpointedCount = ref<number>(0);
const pointedCount = ref<number>(0);
const overLimit = ref<number>(0);
const pdfUrl = ref<string>('');
const waCode = ref(null);
const imageUrl = ref<string>('');

const options = ref<OptionItem[]>([])
const selectedValue = ref('')
const selectedLabel = ref('') 
interface OptionItem {
	label: string;
	value: string;
}

interface pd {
	productBillNo: string,
	productCode: string,
	goodsCode: string,
	goodsName: string,
	designNumberVerSpec: string,
	planQty: number,
	notInQty: number,
	imageUrl: string,
}

// 方法定义
const goBack = () => {
	uni.navigateBack({
	    delta: 1
	});
};

onMounted (() => {
	uni.removeStorageSync('goodsCode')
	uni.removeStorageSync('productCode')
	uni.removeStorageSync('productBillNo')
	uni.removeStorageSync('designNumberVerSpec')
	const user = uni.getStorageSync('user');
	userID.value = user?.id;
	queryWaCode();
})

const queryWaCode = async () => {
	if(userID.value && userID.value.trim() !== ''){
		const res = await uni.request({
			url: `${LAN_URL}${QUERY_WA_URL}`,
			method: 'POST',
			data: {
				userID: userID.value,
				property: '中转点数区域'
			}
		})
		if (res.statusCode === 200) {
		    const data = res.data as any[]
		    options.value = data.map(item => ({
		        label: item.workingAreaName,
		        value: item.workingAreaCode
		    }))
			// 默认为齐套区
			selectedValue.value = options.value[0].value
			selectedLabel.value = options.value[0].label
			waCode.value = selectedValue.value			
		} else {
		    console.error('请求失败', res)
		}
	}else {
		uni.showToast({
			title: '用户信息错误',
			icon: 'none'
		})
	}
}
/* 变更仓库信息 */
const handlePickerChange = (e: any) => {
	const index = e.detail.value
	selectedValue.value = options.value[index].value
	selectedLabel.value = options.value[index].label
	waCode.value = selectedValue.value
	//console.log('选择：', selectedLabel.value, selectedValue.value)
}

const goToDetail = () => {
	if(!productData?.value?.productBillNo) {
		uni.showToast({
			title: '请先查询单据',
			icon: 'none'
		})
		return;
	}
	uni.setStorageSync('goodsCode', productData.value.goodsCode)
	uni.setStorageSync('productCode', productData.value.productCode)
	uni.setStorageSync('productBillNo', productData.value.productBillNo)
	uni.setStorageSync('designNumberVerSpec', productData.value.designNumberVerSpec)
	uni.navigateTo({
		url: '/pages/kittingDetail/kittingDetail'
	})
}

const onAllNumber = () => {
	pointedCount.value = unpointedCount.value
}

const onQuery = async () => {
	pointedCount.value = 0;
	if (!productCodeInput.value || !productCodeInput.value.trim()) {
		uni.showToast({ title: '请输入单据编号', icon: 'none' })
		return;
	}
	try {
		const res = await uni.request({
		  url: `${LAN_URL}${GET_PRODUCT_URL}`, // 改为你的后端地址
		  method: 'POST',
		  data: {
		    productCode: productCodeInput.value,
			waCode: waCode.value
		  }
		});
		if(res.statusCode === 200 && res.data){
			console.log(res.data.id)
			productData.value = {
				productBillNo: res.data.productBillNo,
				productCode: res.data.productCode,
				goodsCode: res.data.goodsCode,
				goodsName: res.data.goodsName,
				designNumberVerSpec: res.data.designNumberVerSpec,
				planQty: res.data.planQty,
				notInQty: res.data.notInQty,
				imageUrl: res.data.imageUrl
			};
			imageUrl.value = productData.value.imageUrl ? `${DOWNLOAD_BASE}${productData.value.imageUrl}` : undefined,
			unpointedCount.value = productData.value.notInQty
			console.log(unpointedCount.value)
			console.log(productData);
			if(unpointedCount.value < 0) {
				overLimit.value = unpointedCount.value * -1;
				unpointedCount.value = 0;
			}else {
				onAllNumber();
				overLimit.value = 0;
			}
		}else {
			uni.showToast({
				title: '数据异常',
				icon: 'none'
			})
		}
	}catch(e) {
		console.log(e)
		console.log('network error')
	}
	
};

/* 扫码 */
const startScan = async () => {
	try {
		const res = uni.scanCode({
			scanType: ['qrCode', 'barCode'],
			onlyFromCamera: true,
			success: (result) => {
				handleScanResult(result)
			},
			fail: (err) => {
				handleScanError(err)
			}
		})
	} catch (error) {
		handleScanError(error)
	}
}
/* 扫码结果处理 */
const handleScanResult = (result: UniApp.ScanCodeSuccessRes) => {
	productCodeInput.value = result.result
	if (result.scanType === 'EAN_13') {
		console.log("1")
	}
	onQuery();
}
/* 扫码错误 */
const handleScanError = (error: any) => {
	console.error('扫码失败:', error)
	uni.showToast({
		title: '扫码失败，请重试',
		icon: 'none'
  })
}

/* 获取原始文件名 */
const getFileNameFromUrl = (url: string) => {
  //处理带参数的URL
  const cleanUrl = url.split('?')[0]
  //获取最后一个斜杠后的内容
  const parts = cleanUrl.split('/')
  return parts[parts.length - 1] || `document_${Date.now()}.pdf` // 默认文件名
}
/* 获取物料编号PDF地址 */
const handleDownloadPdf = async () => {
	if(!productData?.value?.productCode) {
		uni.showToast({
			title: '无法获取单号',
			icon: 'error'
		})
		return;
	}
	uni.request({
		url: `${LAN_URL}${FILE_URL}`,
		method: 'POST',
		data: {
			productCode: productData.value.productCode
		},success:(res) => {
			pdfUrl.value = res.data
			console.log(pdfUrl.value)
			downloadPdf();
		},fail() {
			uni.showToast({
				title: '没有该数据',
				icon: 'none'
			})
		}
	});
}
/* PDF下载 */
const downloadPdf = async () => {
	if(!pdfUrl.value || !pdfUrl.value.trim()) return;
	pdfUrl.value = pdfUrl.value ? `${DOWNLOAD_BASE}${pdfUrl.value}` : undefined
	console.log(pdfUrl.value)
	try {
		const fileName = getFileNameFromUrl(pdfUrl.value)
		const saveDir = '_doc/uniapp_save/'
		
		const { tempFilePath } = await uni.downloadFile({
			url: pdfUrl.value
		})
		let savedPath = '';
		
		// #ifdef MP-WEIXIN
		savedPath = `${uni.env.USER_DATA_PATH}/${Date.now()}.pdf`
		// #endif
	
		// #ifdef APP-PLUS
		savedPath = `${plus.io.convertLocalFileSystemURL(saveDir)}${fileName}`
	
		// #endif
		uni.openDocument({
			filePath: savedPath,
			success: () => {
			    console.log("PDF文件已成功不下载打开");
			},
			fail() {
				uni.saveFile({
					tempFilePath, filePath: savedPath, success(res) {
						console.log("res:" + res.savedFilePath)
						plus.io.resolveLocalFileSystemURL(res.savedFilePath,
							(entry) => {
								console.log("实际存储路径:", "fullPath" + entry.fullPath);
								console.log("savedPath:",savedPath)
								//重命名文件
								plus.io.resolveLocalFileSystemURL(saveDir, (dirEntry) => {
								    entry.moveTo(dirEntry, fileName, (newEntry) => {
								        console.log("文件已重命名:", newEntry.fullPath);
									}, (err) => {
										console.error("文件重命名失败:", err);
									});
								});
							}, 
							(err) => {
								console.log("找不到文件:", err);
							}
						);
						uni.openDocument({
							filePath: res.savedFilePath,
							success: () => {
								console.log("PDF文件已成功打开");
							},
							fail: (err) => {
								console.error("PDF打开失败:", err);
							}
						});
					},fail(err) {
						uni.showToast({ title: '文件不存在', icon: 'error' })
						console.log(err)
					}
				})
			}
		})
	} catch (error) {
		uni.showToast({ title: '文件打开失败', icon: 'none' })
	}
}

const handleSave = () => {
	if(productData.value != null){
		console.log(overLimit.value)
		uni.request({
			url: `${LAN_URL}${ADD_URL}`,
			method: 'POST',
			data: {
				userID: userID.value,
				productBillNo: productData.value.productBillNo,
				waCode: waCode.value,
				inQty: pointedCount.value,
				overInQty: pointedCount.value - productData.value.notInQty > 0 ? pointedCount.value - productData.value.notInQty : 0
			},success: (res) => {
				console.log(res.data)
				if(res.data == 1) {
					uni.showToast({ title: '保存成功', icon: 'none' })
					onQuery();
				}else {
					uni.showToast({ title: '保存失败', icon: 'none' })
				}
			}
		})
	}else {
		uni.showToast({ title: '保存失败', icon: 'error' })
	}
}

const handleImageError = () => {
	imageUrl.value = '/static/images/placeholder.png'
}

// 计算属性（可选）
// const computedValue = computed(() => {
//   return someCalculation();
// });
</script>

<style lang="scss" scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 30rpx;
}

/* 导航栏样式 */
/* .nav-bar {
	background-color: #0078ff;
	color: #fff;
	height: 90rpx;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	position: relative;

	.back-icon {
		font-size: 40rpx;
		margin-right: 20rpx;
	}

	.title {
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
		font-size: 36rpx;
		font-weight: 500;
	}
} */

/* 表单样式 */
.form-container {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	margin-top: -20rpx;
	padding: 30rpx;
}

.form-item {
	display: flex;
	align-items: center;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #eee;

	&:last-child {
		border-bottom: none;
	}	

	.label {
		width: 180rpx;
		font-size: 30rpx;
		color: #333;
	}

	.value-wrapper {
		flex: 1;
		display: flex;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
		justify-content: space-between;
		align-items: center;

		.value {
			color: #666;
			font-size: 30rpx;
		}

		.arrow-icon {
			color: #ccc;
			font-size: 30rpx;
		}
	}
}

/* 扫码查询行 */
.scan-query-row {
	display: flex;
	align-items: center;
	margin: 40rpx 0;

	.scan-input {
		display: flex;
		align-items: center;
		background-color: #f8f8f8;
		padding: 20rpx;
		border-radius: 10rpx;
		margin-right: 20rpx;
		flex: 1;

		.scan-icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 10rpx;
		}

		text {
			font-size: 28rpx;
			color: #666;
		}
	}

	.query-btn {
		background-color: #ff6a00;
		color: #fff;
		font-size: 30rpx;
		padding: 0 40rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
	}
	
	.scan-btn {
		background-color: #0055ff;
		color: #fff;
		font-size: 30rpx;
		padding: 0 40rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		margin-right: 20rpx;
	}
}

/* 任务详情 */
.task-details {
	margin: 30rpx 0;

	.detail-item {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 20rpx;
	}
}

/* 数量信息 */
.quantity-info {
	padding: 30rpx 0;
	border-top: 1rpx solid #eee;
	margin-top: 30rpx;

	.quantity-row {
		display: flex;
		align-items: center;

		text {
			font-size: 30rpx;
			color: #333;
		}

		.unit-button {
			margin: 0 30rpx;
			color: #000000;
			border: none;
		}

		.quantity-input {
			width: 100rpx;
			height: 60rpx;
			text-align: center;
			border: 1rpx solid #ddd;
			border-radius: 6rpx;
			//margin-left: 120rpx;
		}

		.over-limit {
			color: #ff0000;
		}
	}
}

.content-area {
	height: 400rpx; // 占位区域
	background-color: #f9f9f9;
	border-radius: 10rpx;
	padding-bottom: 120rpx
}

/* 底部按钮 */
.footer {
	display: flex;
	height: 50px;
	border-top: 1px solid #f0f0f0;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #ffffff;
}

.footer-btn {
	flex: 1;
	height: 100%;
	line-height: 60px;
	text-align: center;
	font-size: 16px;
	color: #333333;
	background-color: transparent;
	border-radius: 0;
}

.footer-btn.pdfActive {
	background-color: #ff6e30;
	color: #ffffff;
}
</style>